import logging
from typing import List, Optional
from .base import DataSourceProvider, RateData
from .exchangerate_host import ExchangeRateHostProvider
from .frankfurter import FrankfurterProvider

logger = logging.getLogger(__name__)


class DataSourceManager:
    """数据源管理器，支持主备切换"""
    
    def __init__(self):
        self.primary = ExchangeRateHostProvider()
        self.fallback = FrankfurterProvider()
        self.current_provider = self.primary
    
    async def get_latest_rates(self, base: str = "JPY", quotes: List[str] = None) -> List[RateData]:
        """获取最新汇率，支持自动降级"""
        try:
            return await self.current_provider.get_latest_rates(base, quotes)
        except Exception as e:
            logger.warning(f"主数据源 {self.current_provider.get_name()} 失败: {e}")
            
            # 切换到备用数据源
            if self.current_provider == self.primary:
                logger.info(f"切换到备用数据源: {self.fallback.get_name()}")
                self.current_provider = self.fallback
                try:
                    return await self.current_provider.get_latest_rates(base, quotes)
                except Exception as e2:
                    logger.error(f"备用数据源也失败: {e2}")
                    raise e2
            else:
                # 备用数据源也失败，重置为主数据源
                logger.info("重置为主数据源")
                self.current_provider = self.primary
                raise e
    
    async def get_historical_rates(
        self, 
        base: str = "JPY", 
        quotes: List[str] = None,
        start_date = None,
        end_date = None
    ) -> List[RateData]:
        """获取历史汇率，支持自动降级"""
        try:
            return await self.current_provider.get_historical_rates(base, quotes, start_date, end_date)
        except Exception as e:
            logger.warning(f"主数据源 {self.current_provider.get_name()} 获取历史数据失败: {e}")
            
            # 切换到备用数据源
            if self.current_provider == self.primary:
                logger.info(f"切换到备用数据源: {self.fallback.get_name()}")
                self.current_provider = self.fallback
                try:
                    return await self.current_provider.get_historical_rates(base, quotes, start_date, end_date)
                except Exception as e2:
                    logger.error(f"备用数据源也失败: {e2}")
                    raise e2
            else:
                # 备用数据源也失败，重置为主数据源
                logger.info("重置为主数据源")
                self.current_provider = self.primary
                raise e
    
    def get_current_provider_name(self) -> str:
        """获取当前使用的数据源名称"""
        return self.current_provider.get_name()
